/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package portal;

import java.util.Vector;
import javax.portlet.PortletSession;
import javax.portlet.RenderRequest;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import tavernacon.DataValue;

/**
 *
 * @author rory
 */
public class TavernaServer {

    public static String[] getJobs() {

        String[] jobs = null;

        try {
            DocumentBuilderFactory Factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = Factory.newDocumentBuilder();
            Document doc = builder.parse("http://localhost:9090/taverna-server-0.2.1/rest/jobs");
            //creating an XPathFactory:
            XPathFactory factory = XPathFactory.newInstance();
            //using this factory to create an XPath object:
            XPath xpath = factory.newXPath();
            //XPath object created compiles the XPath expression for workflows:
            //XPathExpression WFExpr = xpath.compile("//dataMap/entry/value/list/value/text()");
            XPathExpression jobIDExpr = xpath.compile("//Jobs/job/id/text()");
            Object jobIDResult = jobIDExpr.evaluate(doc, XPathConstants.NODESET);
            NodeList jobIDNodeList = (NodeList) jobIDResult;

            XPathExpression jobWorkflowExpr = xpath.compile("//workflow/text()");
            Object jobWorkflowResult = jobWorkflowExpr.evaluate(doc, XPathConstants.NODESET);
            NodeList jobWorkflowNodeList = (NodeList) jobWorkflowResult;

            XPathExpression jobStatusExpr = xpath.compile("//status/text()");
            Object jobStatusResult = jobStatusExpr.evaluate(doc, XPathConstants.NODESET);
            NodeList jobStatusNodeList = (NodeList) jobStatusResult;



            jobs = new String[jobIDNodeList.getLength()];

            for (int i = 0; i < jobIDNodeList.getLength(); i++) {

                String job = (String) (jobIDNodeList.item(i).getNodeValue());

                jobs[i] = job;

                //results[i] = jobIDNodeList.item(i).getNodeValue();
            }

        } catch (Exception e) {
        }

        System.out.println(jobs);
        return jobs;

    }

    public static Vector getOutputs(PortletSession session) {

        String jobID = (String) session.getAttribute("job");
        final Vector outputs = new Vector();

        try {

            DocumentBuilderFactory Factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = Factory.newDocumentBuilder();

            Document outputsIDDoc = builder.parse("http://localhost:9090/taverna-server-0.2.1/rest/jobs/" + jobID);

            //creating an XPathFactory:
            XPathFactory factory = XPathFactory.newInstance();
            //using this factory to create an XPath object:
            XPath xpath = factory.newXPath();

            XPathExpression outputIDExpr = xpath.compile("//Job/outputs/text()");
            Object outputIDResult = outputIDExpr.evaluate(outputsIDDoc, XPathConstants.NODESET);
            NodeList outputIDNodeList = (NodeList) outputIDResult;

            String outputID = outputIDNodeList.item(0).getNodeValue();
            System.out.println("Output data ID: " + outputID);

            SAXParserFactory SPactory = SAXParserFactory.newInstance();
            SAXParser saxParser = SPactory.newSAXParser();

            DefaultHandler handler = new DefaultHandler() {

                boolean entryFlag = false;
                boolean keyFlag = false;
                boolean valueFlag = false;
                boolean errorFlag = false;
                boolean exceptionFlag = false;
                Vector valuesVector;
                Vector errorsVector;

                public void startElement(String uri, String localName, String qName,
                        Attributes attributes) {


                    System.out.println("Start Element :" + qName);

                    if (qName.equalsIgnoreCase("ENTRY")) {
                        entryFlag = true;
                        errorsVector = new Vector();
                        valuesVector = new Vector();

                    }

                    if (qName.equalsIgnoreCase("KEY")) {
                        keyFlag = true;

                        //HtmlOutputText ot = new HtmlOutputText();

                    }

                    if (qName.equalsIgnoreCase("VALUE") && attributes.getValue("xsi:type") != null) {

                        valueFlag = true;
                    }

                    if (qName.equalsIgnoreCase("CONTAINSERROR")) {
                        errorFlag = true;
                    }

                    if (qName.equalsIgnoreCase("MESSAGE")) {
                        exceptionFlag = true;
                    }


                }

                public void endElement(String uri, String localName,
                        String qName)
                        throws SAXException {

                    System.out.println("End Element :" + qName);

                    if (qName.equalsIgnoreCase("ENTRY")) {
                    }

                }

                public void characters(char ch[], int start, int length)
                        throws SAXException {

                    if (entryFlag) {
                        System.out.println("Entry: " + new String(ch, start, length));
                        entryFlag = false;
                    }

                    if (keyFlag) {
                        System.out.println("Key: " + new String(ch, start, length));

                        keyFlag = false;
                    }

                    if (valueFlag) {
                        System.out.println("Value: " + new String(ch, start, length));
                        String vs = new String(ch, start, length);
                        valuesVector.add(vs);
                        outputs.add(vs);// = vs;

                        //column.getChildren().add(value);
                        valueFlag = false;
                    }

                    if (errorFlag) {

                        System.out.println("Error : " + new String(ch, start, length));
                        String error = new String(ch, start, length);
                        if (error.equals("true")) {
                            errorsVector.add("Errors");
                        } else {
                            errorsVector.add("No errors");
                        }
                        errorFlag = false;
                    }

                    if (exceptionFlag) {
                        String vs = new String(ch, start, length);

                        exceptionFlag = false;
                    }

                }
            };

            saxParser.parse("http://localhost:9090/taverna-server-0.2.1/rest/data/" + outputID, handler);

        } catch (Exception e) {
            e.printStackTrace();
        }
        //outputs.add("asdasdasd");

        return outputs;
    }
}
